package com.gec.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gec.common.R;
import com.gec.dto.LoginUser;
import com.gec.entity.User;
import com.gec.service.UserService;
import com.gec.utils.SMSUtils;
import com.gec.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  移动端用户管理
 * </p>
 *
 * @author : [chenxys]
 * @version : [v1.0]
 * @createTime : [2022/7/15 18:20]
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     * @author chenxys
     * @param user 用户信息
     * @return com.gec.common.R<java.lang.String>
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        // 获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone) && ObjectUtils.isEmpty(redisTemplate.opsForValue().get(phone))){
            // 生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码{}",code);
            // 发送短信
            SMSUtils.sendShortMessage(SMSUtils.QUICK_LOGIN,phone, code);
            // 存入session
            session.setAttribute("code",code);
            // 存入redis
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("短信验证码发送成功");
        }
        return R.success("短信验证码发送失败或已存在有效期内的验证码");
    }

    /**
     * 用户登录
     * @author chenxys
     * @param loginUser 参数
     * @param session 获取验证码
     * @return com.gec.common.R<com.gec.entity.User>
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody LoginUser loginUser,HttpSession session){
        User login = userService.login(loginUser, session);
        if (!ObjectUtils.isEmpty(login)){
            session.setAttribute("user",login);
            return R.success(login);
        }
        // 登录失败
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }
}
